from threading import Thread
# sqlite 文件操作
from ModelDownLoad.SQLite.DbZip import extract_zip
import export
import train
from flask import Flask, render_template, request, redirect, send_from_directory
import subprocess
import os
import yaml
import os
import zipfile
import requests

app = Flask(__name__)
app.template_folder = 'templates'


def extract_zip(zip_file_path, output_dir):
    with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
        zip_ref.extractall(output_dir)

@app.route('/')
def index():
    return render_template('End.html')

# 从Label-studio下载训练数据
@app.route('/export', methods=['POST'])
def export():
    project_id = request.form.get('projectID')
    token = 'dab1b882a8ebfaf7a1b4a9466e33ef781021e056'
    file_path = 'ModelDownLoad'
    file_Name = request.form.get('fileName')

    url = f'http://14.29.241.21:50343/api/projects/{project_id}/export'
    headers = {'Authorization': f'Token {token}'}
    params = {'exportType': 'YOLO', 'download_all_tasks': 'true'}
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    response = requests.get(url, headers=headers, params=params)
    # if response.status_code == 200:
    #     with open(file_path + '/'+file_Name +'.json', 'wb') as file:
    #         file.write(response.content)
    #     return 'JSON content exported successfully.'
    # else:
    #     return 'Error exporting JSON content.'

    if response.status_code == 200:
        file_path = file_path + '/' + file_Name + '.zip'  # 完整的文件路径
        with open(file_path, 'wb') as file:
            file.write(response.content)

        output_dir = 'ModelDownLoad/model_release' #替换为解压缩到的目录路径
        extract_zip(file_path,output_dir)

        return f'image content exported successfully. File saved at: {file_path}'
    else:
        return 'Error exporting image content.'






@app.route('/train', methods=['POST'])
def fishtrain():
    # 规定yaml的地址

    # data_path = request.form['data_path']
    # output_path = request.form['output_path']

    # 构建训练命令
    # train_command = f'conda train.py'

    # 读取yaml 文件
    with open('myfish.yaml','r') as file:
        data = yaml.load(file,Loader=yaml.FullLoader)

    #将路径写入到yaml文件中
    data['path'] = 'D:\\codeHome\\pythoncode\\yoloNext\\yolov5\\ModelDownLoad\\model_release '

    #写入yaml文件
    with open('myfish.yaml','w') as file:
        yaml.dump(data,file)

    


    opt = train.parse_opt()  #.pt
    train.main(opt)

    # 查找runs / train 下的最大目录
    # path = ""
    # path += "weights/best.pt"

    # 导出模型的操作
    # opt = export.parse_opt(output_path, imgsz)  # .bin .xml
    # export.main(opt)

    # 执行训练命令
    # try:
    # t = Thread(target=p, args=(train_command,))
    # t.daemon = True
    # t.start()
    # except subprocess.CalledProcessError as e:
    #     return f'An error occurred: {e}'

    return redirect('/')


def p(train_command):
    subprocess.run(train_command, shell=True, check=True)


@app.route('/import', methods=['POST'])
def import_data():
    # 获取上传的文件
    uploaded_file = request.files['file']

    # 保存文件到指定路径
    file_path = os.path.join('data', uploaded_file.filename)
    uploaded_file.save(file_path)

    return redirect('/')


# @app.route('/export')
# def export_data():
#     # 设置导出文件的路径
#     file_path = 'data/output.txt'
#
#     return send_from_directory('data', filename='output.txt', as_attachment=True)



if __name__ == '__main__':
    app.run(debug=True,port=5003)
